package com.test.demo.mydubbo.framework.protocol.dubbo;

import com.test.demo.mydubbo.framework.protocol.DataFormater;
import com.test.demo.mydubbo.framework.protocol.dubbo.cache.LocalCache;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class NettyServerHandler extends SimpleChannelInboundHandler<DataFormater> {

    //接受客户端的请求并返回结果
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DataFormater dataFormater) throws Exception {
        //处理消费者发出的请求
        //拿出传输的所有信息
        String interfaceName = dataFormater.getInterfaceName();
        //找到对应的实现类
        Class cls = LocalCache.get(interfaceName);
        String methodName = dataFormater.getMethodName();
        Class[] parameterTypes = dataFormater.getParameterTypes();
        Object[] args = dataFormater.getArgs();
        //找到调用方法
        Method declaredMethod = cls.getDeclaredMethod(methodName, parameterTypes);
        //调用方法
        Object result = declaredMethod.invoke(cls.newInstance(), args);
        //把调用结果返回
        channelHandlerContext.channel().writeAndFlush(result);
    }
}
